package com.company.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.common.aop.annotation.LogAnnotation;
import com.company.project.common.utils.Func;
import com.company.project.entity.*;
import com.company.project.mapper.*;
import com.company.project.service.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.util.*;
import java.util.stream.Collectors;

import com.company.project.common.utils.DataResult;

import javax.annotation.Resource;


/**
 * 
 *
 * @author wenbin
 * @email *****@mail.com
 * @date 2023-11-26 08:26:27
 */
@Controller
@RequestMapping("/")
public class TGhkhController {
    @Autowired
    private TGhkhService tGhkhService;
    @Resource
    private TGhszMapper tGhszMapper;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private UserService userService;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private RoleService roleService;
    @Resource
    private TSeatsMapper tSeatsMapper;


    /**
    * 跳转到页面
    */
    @GetMapping("/index/tGhkh")
    public String tGhkh() {
        return "tghkh/list";
        }
    @GetMapping("/index/tGhkh/ghkhedit/{wdkhId}")
    public String wdkhedit(Model model, @PathVariable("wdkhId") String wdkhId) {
        model.addAttribute("wdkhId",wdkhId);
        return "tghkh/ghkheidt";
    }
    @ApiOperation(value = "新增")
    @PostMapping("tGhkh/add")
    @RequiresPermissions("tGhkh:add")
    @LogAnnotation(title = "公海客户", action = "新增")
    @ResponseBody
    public DataResult add(@RequestBody TGhkhEntity tGhkh){
        tGhkhService.save(tGhkh);
        return DataResult.success();
    }
    @ApiOperation(value = "领取")
    @PostMapping("tGhkh/lingqu")
    @LogAnnotation(title = "公海客户", action = "领取")
    @ResponseBody
    public DataResult lingqu(@RequestBody @ApiParam(value = "id集合") List<String> ids){
        return tGhkhService.lingqu(ids);
    }
    @ApiOperation(value = "分配")
    @PostMapping("tGhkh/fenpei")
    @LogAnnotation(title = "公海客户", action = "分配")
    @ResponseBody
    public DataResult fenpei(@RequestBody @ApiParam(value = "id集合与username") Map<String,Object> map){
        return tGhkhService.fenpei(map);
    }
    @ApiOperation(value = "删除")
    @DeleteMapping("tGhkh/delete")
    @RequiresPermissions("tGhkh:delete")
    @LogAnnotation(title = "公海客户", action = "删除")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){
        TSeatsEntity tSeats = userService.getTSeats();
        TGhkhEntity byId = tGhkhService.getById(ids.get(0));
        tGhkhService.removeByIds(ids);
        TGhszEntity tGhszEntity = tGhszMapper.selectList(Wrappers.<TGhszEntity>lambdaQuery().eq(TGhszEntity::getGhmc, byId.getSsgh()).eq(TGhszEntity::getSsgs, tSeats.getCorporatename())).get(0);
        //变更客户数量
        tGhszEntity.setKhsl(tGhszEntity.getKhsl() - ids.size());
        tGhszMapper.updateById(tGhszEntity);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("tGhkh/update")
    @RequiresPermissions("tGhkh:update")
    @ResponseBody
    public DataResult update(@RequestBody TGhkhEntity tGhkh){
        tGhkhService.updateById(tGhkh);
        return DataResult.success();
    }

    @ApiOperation(value = "查询分页数据")
    @PostMapping("tGhkh/listByPage")
    @LogAnnotation(title = "公海客户", action = "查询分页数据")
    @RequiresPermissions("tGhkh:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody TGhkhEntity tGhkh){
        Page page = new Page(tGhkh.getPage(), tGhkh.getLimit());
        IPage<TGhkhEntity> iPage = null;
        LambdaQueryWrapper<TGhkhEntity> queryWrapper = Wrappers.lambdaQuery();
        //客户来源
        if (Func.isNotBlank(tGhkh.getKhly())) {
            queryWrapper.eq(TGhkhEntity::getKhly, tGhkh.getKhly());
        }
        //入公海原因
        if (Func.isNotBlank(tGhkh.getRghyy())) {
            queryWrapper.eq(TGhkhEntity::getRghyy, tGhkh.getRghyy());
        }

        Calendar calendar = Calendar.getInstance();
        //入公海时间
        if (Func.isNotEmpty(tGhkh.getRktimeS())) {
            calendar.setTime(tGhkh.getRktimeE());
            calendar.add(Calendar.DAY_OF_MONTH,1);
            queryWrapper.between(TGhkhEntity::getRktime, tGhkh.getRktimeS(),calendar.getTime());
        }
        //所属公海
        if(Func.isNotEmpty(tGhkh.getSsgh())) {
            String ssgh = tGhkh.getSsgh();
            if (ssgh.indexOf(";")>-1){
                String[] split = ssgh.split(";");
                queryWrapper.eq(TGhkhEntity::getSsgh, split[0]);
                queryWrapper.eq(TGhkhEntity::getSsghid, split[1]);
            } else {
                queryWrapper.eq(TGhkhEntity::getSsgh, tGhkh.getSsgh());
            }
        } else {
            //只看自己的公海客户
            String userId = httpSessionService.getCurrentUserId();
            SysUser sysUser = userService.getById(userId);
            List<SysRole> roleInfoByUserId = roleService.getRoleInfoByUserId(userId);
            List<String> collect = roleInfoByUserId.stream().map(e -> e.getName()).collect(Collectors.toList());
            List<Object> ghmcs = new ArrayList<>();
            if (collect.contains("超级管理员") || collect.contains("代理商")) {
                List<Object> corporatenames = tSeatsMapper.selectObjs(Wrappers.<TSeatsEntity>lambdaQuery().select(TSeatsEntity::getCorporatename).eq(TSeatsEntity::getCreateuser, sysUser.getUsername()));
                if (Func.isNotEmpty(corporatenames)) {
                    ghmcs = tGhszMapper.selectObjs(Wrappers.<TGhszEntity>lambdaQuery().select(TGhszEntity::getId)
                            .in(TGhszEntity::getGhmc, corporatenames));
                }
            }
            if (Func.isEmpty(ghmcs)) {
                SysDept sysDept = sysDeptMapper.selectOne(Wrappers.<SysDept>lambdaQuery()
                        .eq(SysDept::getId, sysUser.getDeptId()));
                ghmcs = tGhszMapper.selectObjs(Wrappers.<TGhszEntity>lambdaQuery()
                        .select(TGhszEntity::getId)
                        .like(TGhszEntity::getGhcy, userId)
                        .or()
                        .like(TGhszEntity::getGhgly, userId)
                        .or()
                        .like(TGhszEntity::getGhcybm, sysDept.getId()));
            }
            if (Func.isEmpty(ghmcs)) {
                return DataResult.success(iPage);
            }
            queryWrapper.in(TGhkhEntity::getSsghid, ghmcs);
        }
        queryWrapper.orderByDesc(TGhkhEntity::getRktime);
            iPage = tGhkhService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }
    @ApiOperation(value = "查询初始化选项")
    @LogAnnotation(title = "公海客户", action = "查询初始化选项")
    @GetMapping("tGhkh/infoData")
    @ResponseBody
    public DataResult infoData(){
        return tGhkhService.infoData();
    }
    @ApiOperation(value = "查询详情")
    @LogAnnotation(title = "公海客户", action = "查询详情")
    @PostMapping("tGhkh/infoDataById/{wdkhId}")
    @ResponseBody
    public DataResult getDataById(@PathVariable("wdkhId") String wdkhId) {
        return tGhkhService.getDataById(wdkhId);
    }

}
